//
//  PublishPostontroller.m
//  Qzone
//
//  Created by zhangxy on 2018/7/19.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "PublishPostontroller.h"

#import "ZTextView.h"
#import "ChooseTypeController.h"
#import "ChooseLabelController.h"
#import "NavTypeEntity.h"

#import "MyButton.h"
#import "XHImageViewer.h"

#import "RITLPhotos.h"

#import "UIView+Border.h"

@interface PublishPostontroller ()<ImagePickerDelegate,UITextViewDelegate,RITLPhotosViewControllerDelegate>{
    UIButton *curBtn;
    
    NavTypeEntity *checkType;
}

@property(nonatomic,strong) UIView *conentView;
@property(nonatomic,strong) ZTextView *titleView;
@property(nonatomic,strong) ZTextView *textView;

@property(nonatomic,strong) UIScrollView *mainScroll;
@property(nonatomic,strong) UIView *menuScroll;
@property(nonatomic,strong) NSMutableDictionary *photos;
@property(nonatomic,strong) NSMutableArray *waitUploadData;
@property(nonatomic,strong) NSMutableArray *labels;

@end

@implementation PublishPostontroller

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"";
    [self setNavigationBar];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0,0,56,26)];
    [button setBackgroundColor:UIColorFromRGBAlpha(TextWhiteColor, 0.3)];
    [button setTitle:@"发布" forState:0];
    [button.titleLabel setFont:FontFiftent];
    button.layer.cornerRadius = 8.0f;
    button.layer.masksToBounds = YES;
    [button addTarget:self action:@selector(publishAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = btn;
    self.navigationController.navigationBarHidden = NO;
    
    _photos = [[NSMutableDictionary alloc] init];
    _labels = [[NSMutableArray alloc] init];
    _waitUploadData = [[NSMutableArray alloc] init];
    
//    checkType = [[NavTypeEntity alloc] init];
//    checkType.nav_type = @"forum";
//    checkType.nav_name = @"帖子";
//    checkType.nav_id  = @"0";
    
    [self createViewByType];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(allHideKeyBoard)];
    self.view.userInteractionEnabled = YES;
    [self.view addGestureRecognizer:tap];
}

-(void)publishAction{
    // 发布
    // 素材
    if(checkType == nil){
        [PopUtil showMessage:@"请选项分类" positionType:PopPositionTypeMiddle];
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self uploadImages];
//    NSString *strTag = @"";
//    for (NavTypeEntity *tagItem in _labels) {
//        strTag = [strTag stringByAppendingFormat:@"%@,",tagItem.tag_id];
//    }
//    if(strTag.length>0){
//        strTag = [strTag substringToIndex:strTag.length - 1];
//    }
}

-(void)publishSucai{
    NSString *str = @"";
    for (NSDictionary *dict in _photos.allValues) {
        str = [str stringByAppendingFormat:@"%@,",dict[@"image_id"]];
    }
    
    if(str.length>0){
        str = [str substringToIndex:str.length - 1];
    }
    
    [NetworkUtil POST:API_publishPost
           parameters:@{@"session_uid":[UserUtil getUser].user_id,
                        @"action_type":@"add",
                        @"thread_id":@"",
                        @"title":convertToString(_titleView.text),
                     @"message":convertToString(_textView.text),
                     @"cat_id":checkType.cat_id,
                     @"img_id":str
                     } success:^(id responseObject, NSDictionary *dict) {
                         [MBProgressHUD hideHUDForView:self.view animated:YES];
                         [PopUtil showMessage:dict[@"msg"]];
                         [self backAction];
                     } failure:^(NSError *error, NSString *message) {
                         [MBProgressHUD hideHUDForView:self.view animated:YES];
                         [PopUtil showMessage:message];
                         
                     }];
}




-(void)createViewByType{
    _conentView = [[UIView alloc] initWithFrame:CGRectMake(15, 0, ScreenWidth-30, 138)];
    
    _titleView = [self createTextView];
    [_titleView setFrame:CGRectMake(0, 10, ScreenWidth - 30, 40)];
    [_titleView addBottomBorderWithColor:UIColorFromRGB(BgLineColor) andWidth:1.0f];
    [self.titleView setPlaceholder:@"帖子标题.."];

    _textView = [self createTextView];
    [_textView setFrame:CGRectMake(0, 64, ScreenWidth - 30, 64)];
    [_textView addBottomBorderWithColor:UIColorFromRGB(BgLineColor) andWidth:1.0f];
    [self.textView setPlaceholder:@"帖子内容.."];
    
    [_conentView addSubview:_titleView];
    [_conentView addSubview:_textView];
    [self.view addSubview:_conentView];
    


    _mainScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 148, ScreenWidth, 108)];
    [_mainScroll setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_mainScroll];
    
    _mainScroll.showsHorizontalScrollIndicator = NO;
    _mainScroll.showsVerticalScrollIndicator = NO;
    _mainScroll.alwaysBounceHorizontal = YES;
    _mainScroll.alwaysBounceVertical = NO;
    _mainScroll.pagingEnabled = NO;
    //    _mainScroll.bounces = NO;
    _mainScroll.scrollEnabled = YES;
    
    
    [self createShareButton:(int)_waitUploadData.count + 1];
    
    
    _menuScroll = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_mainScroll.frame) + 10, ScreenWidth, 108)];
    [_menuScroll setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_menuScroll];
    
    
    UIButton *btn = [self createButton];
    btn.layer.cornerRadius = 8.0f;
    btn.layer.masksToBounds = YES;
    btn.layer.borderWidth = 1.0f;
    btn.layer.borderColor = UIColorFromRGB(BgTitleColor).CGColor;
    [btn setFrame:CGRectMake(20, 0, 88, 30)];
    [btn setTitle:@"选择分类" forState:0];
    btn.tag = 3;
    [btn setTitleColor:UIColorFromRGB(BgTitleColor) forState:0];
    [btn addTarget:self action:@selector(tagClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.menuScroll addSubview:btn];
}


- (ZTextView *)createTextView
{
    ZTextView  *textView = [[ZTextView alloc] init];
    textView.frame = CGRectMake(15,64,SCREEN_WIDTH - 30, 140);
    //        _textView.textContainerInset = UIEdgeInsetsMake(5, 5, 5, 5);
    textView.placeholder = self.navigationItem.title;
    textView.placeholderColor = LIGHT_GRAY_COLOR;
    textView.textColor = UIColorFromRGB(TextSizeEightColor);
    textView.delegate = self;
    textView.font = FontFiftent;
    //        _textView.inputAccessoryView = self.keyboardView;
    textView.showsVerticalScrollIndicator = NO;
//    [textView becomeFirstResponder];  //弹出键盘
    return textView;
}






-(void)tagClick:(UIButton *)btn{
    
    ChooseTypeController *vc = [[ChooseTypeController alloc] init];
    [vc setZZChooseResultBlock:^(id tagObj) {
        self->checkType = tagObj;
        
        [btn setTitle:convertToString(self->checkType.cat_name) forState:0];
    }];
    [self openPushVC:vc];
//
//    // 话题
//    if(checkType == nil){
//        [PopUtil showMessage:@"请先选择分类!"];
//        return;
//
//    }
//    ChooseLabelController *vc = [[ChooseLabelController alloc] init];
//    vc.type = (int)btn.tag;
//    vc.entity = checkType;
//    [vc setZZChooseResultBlock:^(id tagObj) {
//        NavTypeEntity *typeItem = tagObj;
//        BOOL isHad = NO;
//        for (NavTypeEntity *item in _labels) {
//            if([typeItem.tag_id isEqual:item.tag_id]){
//                isHad = YES;
//                break;
//            }
//        }
//
//        if(!isHad){
//            [_labels addObject:tagObj];
//            [self reSetButtonLocation];
//        }
//
//    }];
//    [self openPushVC:vc];
}


-(void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)reSetButtonLocation{
    // 获取标签的控件
    UIButton *btnLabel = [_menuScroll viewWithTag:2];
    
    // 是否公开按钮
    UIButton *btnSecret = [_menuScroll viewWithTag:4];
    
    for (MyButton *btn in _menuScroll.subviews) {
        if(btn.tag >= 100){
            [btn removeFromSuperview];
        }
    }
    
    CGRect sf = CGRectMake(118, 0, 88, 30);
    
    CGFloat x = sf.origin.x;
    CGFloat y = sf.origin.y;
    
    for (int i = 0; i<_labels.count; i++) {
        NavTypeEntity *entity = [_labels objectAtIndex:i];
        MyButton *btn = [MyButton buttonWithType:UIButtonTypeCustom];
        [btn.titleLabel setFont:FontFiftent];
        [btn setTitleColor:UIColorFromRGB(TextSizeEightColor) forState:0];
        btn.layer.cornerRadius = 8.0f;
        btn.layer.masksToBounds = YES;
        btn.layer.borderWidth = 1.0f;
        btn.layer.borderColor = UIColorFromRGB(BgListSectionColor).CGColor;
        btn.objTag = entity;
        btn.tag = 100+i;
        [btn setTitle:[NSString stringWithFormat:@"%@ x",entity.tag_name] forState:0];
        [btn addTarget:self action:@selector(closeTagButton:) forControlEvents:UIControlEventTouchUpInside];
        
        CGSize s = [self autoWidthOfLabel:btn.titleLabel with:sf.size.height];
        if(ScreenWidth - x - s.width > 30){
            [btn setFrame:CGRectMake(x, y, s.width+10, sf.size.height)];
        }else{
            y = y + 40;
            x = 20;
            [btn setFrame:CGRectMake(x, y, s.width+10, sf.size.height)];
        }
        x = x + s.width + 20;
        
        [_menuScroll addSubview:btn];
    }
    
    if(ScreenWidth - x - 88 < 10){
        y = y + 40;
        x = 20;
    }
    [btnLabel setFrame:CGRectMake(x, y, 88, 30)];
    x = x + 88 + 10;
    
    if(btnSecret){
        if(ScreenWidth - x - 88 > 10){
            [btnSecret setFrame:CGRectMake(x, y, 88, 30)];
        }else{
            y = y + 40;
            x = 20;
            [btnSecret setFrame:CGRectMake(x, y, 88, 30)];
        }
    }
}

-(void)closeTagButton:(MyButton *) btn{
    NavTypeEntity *obj = btn.objTag;
    [_labels removeObject:obj];
    [self reSetButtonLocation];
}

-(UIButton *)createShareButton:(int) i{
    CGFloat itemW = 108;
    CGFloat x = 20 + (i-1)*itemW + (i-1)*10;
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
    [btn setFrame:CGRectMake(x, 0, itemW, itemW)];
    btn.tag = i;
    btn.layer.cornerRadius = 3.0f;
    btn.layer.masksToBounds  = YES;
    [btn setTitleColor:DEEP_GRAY_COLOR forState:UIControlStateNormal];
    [btn.imageView setContentMode:UIViewContentModeScaleAspectFill];
    [btn setImage:[UIImage imageNamed:@"发布 添加图片"] forState:0];
    [btn addTarget:self action:@selector(addWithButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [_mainScroll addSubview:btn];
    
    [_mainScroll setContentSize:CGSizeMake(x + 108, 108)];
    
    curBtn = btn;
    
    return btn;
}

-(void)addWithButton:(UIButton *) btn{
    if(_waitUploadData.count > 0 && btn.tag <= _waitUploadData.count){
        UIImageView *_picView = (UIImageView*)btn.imageView;
        
        CALayer *calayer = _picView.layer.mask;
        [_picView.layer.mask removeFromSuperlayer];
        
        XHImageViewer *xh = [[XHImageViewer alloc] initWithImageViewerWillDismissWithSelectedViewBlock:^(XHImageViewer *imageViewer, UIImageView *selectedView) {
            
        } didDismissWithSelectedViewBlock:^(XHImageViewer *imageViewer, UIImageView *selectedView) {
            
            selectedView.layer.mask = calayer;
            [selectedView setNeedsDisplay];
            
            [btn sendSubviewToBack:_picView];
            
        } didChangeToImageViewBlock:^(XHImageViewer *imageViewer, UIImageView *selectedView) {
        }];
        
        NSMutableArray *photos = [[NSMutableArray alloc] init];
        [photos addObject:_picView];
        
        //    xh.delegate = self;
        xh.disableTouchDismiss = NO;
        [xh showWithImageViews:photos selectedView:_picView];
        return;
    }
    
    
    [[ImagePickerUtil defaultPicker] startPickerWithController:self title:@"选择图片" checkBlock:^(UIImagePickerControllerSourceType type) {
        if(type == UIImagePickerControllerSourceTypePhotoLibrary){
            
            RITLPhotosViewController *photoController = [RITLPhotosViewController photosViewController];
            photoController.configuration.maxCount = 25;//最大的选择数目
            photoController.configuration.containVideo = false;//选择类型，目前只选择图片不选择视频
            photoController.photo_delegate = self;
            photoController.thumbnailSize = btn.frame.size;//缩略图的尺寸
            
            [self presentViewController:photoController animated:true completion:^{}];
        }
    }];
    
    curBtn = btn;
}
/**
 选中图片以及视频等资源的数据
 根据是否选中原图所得
 如果为原图，则返回原图大小的数据
 如果不是原图，则返回原始比例的数据
 注: 不会返回thumbnailImages的数据大小
 
 @param viewController RITLPhotosViewController
 @param datas 选中资源的数据
 */
- (void)photosViewController:(UIViewController *)viewController
                       datas:(NSArray <NSData *> *)datas{
    for(NSData *data in datas){
        UIImage *img = [UIImage imageWithData:data];
        [curBtn setImage:img forState:UIControlStateNormal];
        
        UIImageView *imgView = [self createImageView];
        imgView.tag = curBtn.tag + 100;
        [imgView setImage:[UIImage imageNamed:@"btn_publish_close_material"]];
        [imgView setFrame:CGRectMake(108-30, 0, 30, 30)];
        imgView.userInteractionEnabled = YES;
        [imgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(delClick:)]];
        [curBtn addSubview:imgView];
        
        
        [_waitUploadData addObject:UIImageJPEGRepresentation(img,0.5)];
        
        [self createShareButton:_waitUploadData.count + 1];
    }
}
- (void)photosViewController:(UIViewController *)viewController
                      images:(NSArray <UIImage *> *)images{
    
}


-(void)delClick:(UITapGestureRecognizer *) tap{
    UIImageView *img = (UIImageView *)tap.view;
    int tag = (int)img.tag - 100;
    if(_waitUploadData.count > 0 && tag <= _waitUploadData.count){
        [[AlertUtil shareInstance] showSheet:@"删除图片吗？" message:@"" cancelTitle:@"取消" titleArray:@[@"删除"] viewController:self confirm:^(NSInteger buttonTag) {
            
            if(buttonTag<0){
                // 取消
            }else if(buttonTag == 0){
                UIButton *btn = [self.mainScroll viewWithTag:tag];
                int index = (int)tag+1;
                int count = (int)self.waitUploadData.count + 1;
                
                [btn removeFromSuperview];
                
                for(int i = index;i<=count;i++){
                    UIButton *button = [self.mainScroll viewWithTag:i];
                    UIImageView *img = [button viewWithTag:button.tag+100];
                    if(img){
                        img.tag = img.tag - 1;
                    }
                    button.tag = button.tag - 1;
                    
                    CGRect f = button.frame;
                    f.origin.x = f.origin.x - 118;
                    button.frame = f;
                }
                [self.photos removeObjectForKey:self.waitUploadData[btn.tag - 1]];
                [self.waitUploadData removeObjectAtIndex:btn.tag-1];
            }
        }];
        return;
    }
}

#pragma mark - imageView delegate
- (void)imagePickerDidFinishedWithInfo:(NSDictionary *)info image:(UIImage *)thumIamge file:(NSURL *)url type:(ImagePickerDelegateType)type{
    
    NSData *data = UIImageJPEGRepresentation(thumIamge,0.5);
    //    OssUploadType ossType = OssUploadTypeImage;
    if(type == ImagePickerDelegateImage){
        [curBtn setImage:thumIamge forState:UIControlStateNormal];
        
        UIImageView *imgView = [self createImageView];
        imgView.tag = curBtn.tag + 100;
        [imgView setImage:[UIImage imageNamed:@"btn_publish_close_material"]];
        [imgView setFrame:CGRectMake(108-30, 0, 30, 30)];
        imgView.userInteractionEnabled = YES;
        [imgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(delClick:)]];
        [curBtn addSubview:imgView];
        
        [_waitUploadData addObject:data];
        
        [self createShareButton:(int)_waitUploadData.count + 1];
    }
}

-(void)uploadImages{
    if(self.waitUploadData.count == _photos.allKeys.count){
        [self publishSucai];
        return;
    }
    [self.waitUploadData enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSData *data = obj;
        if([self->_photos objectForKey:obj]==nil){
            [ImageUploadUtil updateImage:data type:@"forum" callback:^(NSString *imageurl, NSDictionary *videoDict,NSString *message) {
                DLog(@"%@",imageurl);
                NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:videoDict];
                [params setObject:data forKey:@"data"];
                if(convertToString(imageurl).length==0){
                    [PopUtil showMessage:message positionType:PopPositionTypeMiddle];
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                }else{
                    [self->_photos setObject:videoDict forKey:obj];
                    
                    if(self.waitUploadData.count == self->_photos.count){
                        [self publishSucai];
                    }
                    
                }
            }];
        }
    }];
}



#pragma mark - textview delegate
- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.markedTextRange == nil) {
        textView.attributedText = [textView.text formatWithParagraph:5.0 fontSize:15 textColor:[UIColor blackColor]];
    }
}



-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self allHideKeyBoard];
}

- (void)allHideKeyBoard
{
    for (UIWindow* window in [UIApplication sharedApplication].windows)
    {
        for (UIView* view in window.subviews)
        {
            [self dismissAllKeyBoardInView:view];
        }
    }
}

-(BOOL) dismissAllKeyBoardInView:(UIView *)view
{
    if([view isFirstResponder])
    {
        [view resignFirstResponder];
        return YES;
    }
    for(UIView *subView in view.subviews)
    {
        if([self dismissAllKeyBoardInView:subView])
        {
            return YES;
        }
    }
    return NO;
}

// 隐藏键盘
-(void)downKeyBoard:(id)sender{
    [self allHideKeyBoard];
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch {
    
    if ([touch.view isKindOfClass:[UIScrollView class]]) {
        
        return YES;
        
    }
    
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/**
 计算Label高度
 
 @param label 要计算的label，设置了值
 @param width label的最大宽度
 */
- (CGSize )autoWidthOfLabel:(UILabel *)label with:(CGFloat )height{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(FLT_MAX, height);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.width = expectedLabelSize.width;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
